package com.zimmor.rocketmq.lisenter;

import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.messaging.Message;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author:zimmor
 * @Date: 2023/2/20 9:38
 * @Description
 * @version: 1.0.0
 */
@RocketMQTransactionListener
public class TransationLisener implements RocketMQLocalTransactionListener {
    Map map = new HashMap<>();
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        RocketMQLocalTransactionState state = RocketMQLocalTransactionState.UNKNOWN;
        //模拟本地事务
        boolean status = false;

        try {
//            int i = 1/0;
            if(status) {
                state = RocketMQLocalTransactionState.COMMIT;
            }
            map.put("TransactionId", message.getHeaders().get("rocketmq_TRANSACTION_ID"));

        }catch (Exception e) {
            e.printStackTrace();
            state = RocketMQLocalTransactionState.ROLLBACK;
        }

        return state;
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        RocketMQLocalTransactionState state = RocketMQLocalTransactionState.UNKNOWN;

        try {
//            int i = 1/0;
            Object transactionId = map.get("TransactionId");
            if(transactionId != null) {
                state = RocketMQLocalTransactionState.COMMIT;
            } else {
                state = RocketMQLocalTransactionState.ROLLBACK;
            }
        }catch (Exception e) {
            e.printStackTrace();
        }

        return state;
    }
}
